package com.sxt.practiceapplication.utils

import android.content.Context
import android.content.Intent
import com.lzy.okhttputils.OkHttpUtils
import com.lzy.okhttputils.cache.CacheMode
import com.lzy.okhttputils.callback.StringCallback
import com.sxt.practiceapplication.activities.LoginActivity
import com.sxt.practiceapplication.common.Constants
import com.sxt.practiceapplication.common.ServerStatus
import com.sxt.practiceapplication.common.Urls
import com.sxt.practiceapplication.entity.user.LoginData
import com.sxt.practiceapplication.entity.user.data.UserQueryData
import okhttp3.Call
import okhttp3.Response

object LoginUser {

    private const val USER_TOKEN = "user_token"

    private const val USER_ID = "user_id"

    @JvmStatic
    @JvmOverloads
    fun checkAndToLogin(context: Context, target: Intent? = null): Boolean {
        val token = CacheUtils.getString(context, USER_TOKEN)
        if (token == null) {
            val intent = Intent(context, LoginActivity::class.java)
            intent.putExtra("target", target)
            context.startActivity(intent)
            return false
        }
        return true
    }

    @JvmStatic
    fun logout(context: Context) {
        ToastUtils.show("已退出登录")
        CacheUtils.remove(context, USER_TOKEN)
        CacheUtils.remove(context, USER_ID)
        sendBroadCast(context)
    }

    @JvmStatic
    fun isLogin(context: Context): Boolean {
        return CacheUtils.getString(context, USER_TOKEN) != null
    }

    @JvmStatic
    fun login(context: Context, loginToken: String, id: Int) {
        ToastUtils.show("登录成功")
        CacheUtils.putString(context, USER_TOKEN, loginToken)
        CacheUtils.putInt(context, USER_ID, id)
        sendBroadCast(context)
    }

    @JvmStatic
    fun getCurrentUserData(context: Context): LoginData {
        return LoginData(
                CacheUtils.getString(context, USER_TOKEN),
                CacheUtils.getInt(context, USER_ID)
        )
    }

    private fun sendBroadCast(context: Context) {
        context.sendBroadcast(Intent(Constants.LOGIN_STATE_CHANGE))
    }

    @JvmStatic
    fun loginStateCheck(context: Context) {
        val userData = getCurrentUserData(context)
        if (userData.userId > 0) {
            OkHttpUtils.get(Urls.USER_QUERY_URL + userData.userId)
                    .tag(this)
                    .cacheMode(CacheMode.NO_CACHE)
                    .headers("Authorization", userData.token)
                    .execute(object : StringCallback() {
                        override fun onSuccess(result: String, call: Call, response: Response) {
                            val userQueryData = GsonBinder.toObj(result, UserQueryData::class.java)
                            if (userQueryData.code == ServerStatus.AUTH_ERROR.code) {
                                Tools.showErrorDialog(context, userQueryData.message)
                                logout(context)
                            }
                        }

                        override fun onError(call: Call, response: Response, e: Exception) {
                            Tools.showEnsureDialog(context, "登录状态发生改变", "用户检测失败, 请重新登录")
                            logout(context)
                        }
                    })
        }
    }
}